import xlsx from "node-xlsx";
import { dirname, join } from "path";
import fs from "fs";
import { fileURLToPath } from "url";
import XLSX from "xlsx";
import { log } from "./logs";

const __dirname = dirname(fileURLToPath(import.meta.url));

export interface XlxsDocument {
  name: string;
  data: any[][];
}

export interface Xlsx {
  file?: string;
  document?: XlxsDocument[];
}

/**
 * 读取xlsx文件
 * @param file
 * @param cwd
 * @returns
 */
export const read = async (file: string, cwd: string): Promise<Xlsx> => {
  try {
    const filepath = join(cwd, file);
    const workbook = XLSX.readFile(filepath);
    const props = workbook.Workbook?.Sheets?.reduce((acc: any, curr: any) => {
      acc[curr?.name] = curr;
      return acc;
    }, {} as Record<string, any>);
    const content = await fs.promises.readFile(filepath);
    const document = xlsx
      .parse(content)
      ?.filter((sheet) => !props?.[sheet?.name]?.Hidden);
    await log(file, `origin.xlsx`, content)
    return {
      file,
      document,
    };
  } catch (error) {
    console.error(`读取xlsx文件${file}出错：`, error);
    return {
      file,
      document: [],
    };
  }
};

/**
 * 写入xlsx文件
 * @param file 
 * @param cwd 
 * @param sheetName 
 * @param headers 
 * @param data 
 */
export const write = async (
  file: string,
  sheetName: string,
  headers: string[],
  data: any[][],
  cwd: string = join(__dirname, '../../logs')
) => {
  const filepath = join(cwd, file);
  let workbook;
  
  // 检查文件是否存在
  if (fs.existsSync(filepath)) {
    // 如果文件存在，读取现有workbook
    workbook = XLSX.readFile(filepath);
    
    // 检查是否已存在同名sheet
    const existingSheet = workbook.SheetNames.indexOf(sheetName);
    if (existingSheet >= 0) {
      // 如果存在同名sheet，删除它
      workbook.SheetNames.splice(existingSheet, 1);
      delete workbook.Sheets[sheetName];
    }
  } else {
    // 如果文件不存在，创建新workbook
    workbook = XLSX.utils.book_new();
  }
  
  // 创建新worksheet并添加到workbook
  const worksheet = XLSX.utils.aoa_to_sheet([headers, ...data]);
  XLSX.utils.book_append_sheet(workbook, worksheet, sheetName);
  
  // 写入文件
  XLSX.writeFile(workbook, filepath);
};
